package com.example.chamberlainserver.Service;

import com.example.chamberlainserver.security.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Token验证服务
 * 提供JWT Token验证相关功能
 */
@Service
public class TokenValidationService {

    @Autowired
    public JwtTokenUtil jwtTokenUtil;

    /**
     * 验证Token是否有效
     *
     * @param token JWT Token
     * @param authentication 认证信息
     * @return 是否有效
     */
    public boolean validateToken(String token, Authentication authentication) {
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }

        if (token == null || token.isEmpty()) {
            return false;
        }

        try {
            // 验证token是否有效
            if (authentication.getPrincipal() instanceof UserDetails) {
                UserDetails userDetails = (UserDetails) authentication.getPrincipal();
                return jwtTokenUtil.validateToken(token, userDetails);
            } else {
                System.out.println("TokenValidationService: 认证主体不是UserDetails");
                return false;
            }
        } catch (Exception e) {
            System.out.println("TokenValidationService: Token验证异常: " + e.getMessage());
            return false;
        }
    }

    /**
     * 从请求头中提取Token
     *
     * @param authorizationHeader Authorization请求头
     * @return JWT Token，如果无效则返回null
     */
    public String extractTokenFromHeader(String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            return null;
        }
        return authorizationHeader.substring(7);
    }
    
    /**
     * 检查Token是否过期
     *
     * @param jwtToken JWT Token
     * @return 如果Token未过期则返回true，否则返回false
     */
    public boolean isTokenNotExpired(String jwtToken) {
        try {
            // 获取token的过期时间
            Date expirationDate = jwtTokenUtil.getExpirationDateFromToken(jwtToken);
            // 检查是否过期（当前时间是否在过期时间之后）
            return !expirationDate.before(new Date());
        } catch (Exception e) {
            System.out.println("TokenValidationService: 检查Token过期异常: " + e.getMessage());
            return false;
        }
    }
}